package com.example.crm.servlet;

import com.example.crm.pojo.Customer;
import com.example.crm.service.CustomerService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

/**
 * @Author AthenaKnovesp
 */

@WebServlet(value = "/customer/add")
public class CustomerAddServlet extends HttpServlet {

    CustomerService customerService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.getRequestDispatcher("/WEB-INF/jsp/customer/add.jsp").forward(req, resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        Customer customer = new Customer();
        try {
            BeanUtils.populate(customer, req.getParameterMap());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());

        customerService = (CustomerService) applicationContext.getBean("customerService");

        int i = customerService.addCustomer(customer);
        if (i == 1) {
            resp.sendRedirect("/customer/list");
        }
    }
}